﻿using System;
using System.Net;
using System.Threading.Tasks;
using Hn.Database.DAL;
using Hn.Database.Enum;
using Microsoft.Extensions.Logging;
using SuperSocket;
using SuperSocket.Channel;
using SuperSocket.Server;

namespace MSocketCore.MSocket
{
    public class MySession : AppSession
    {
        private readonly ILogger<MySession> _logger;

        public MySession(ILogger<MySession> logger)
        {
            _logger = logger;
        }

        protected override async ValueTask OnSessionConnectedAsync()
        {
            var ip =(IPEndPoint)this.RemoteEndPoint;
           _logger.LogInformation($"AppClient Connect :{ip.Address} : {ip.Port}");
        }

        protected override async ValueTask OnSessionClosedAsync(CloseEventArgs e)
        {
            var ip = (IPEndPoint)this.RemoteEndPoint;
            if (Sn !=null)
            {
                DtuDAL.UpdateOnline(Sn, OnlineType.Offline);
            }
            
            _logger.LogInformation($"AppClient Disconnect :{ip.Address} : {ip.Port} Reason :{ e.Reason }");
        }

        public ValueTask SendAsync(ReadOnlyMemory<byte> data)
        {
            _logger.LogInformation($"AppSever Send :{BitConverter.ToString(data.ToArray()).Replace("-"," ")}");
            return ((IAppSession)this).SendAsync(data);
        }

        public string Sn { get; set; }

        public int Seq { get; set; }

        public bool IsBusy { get; set; }
    }
}
